package com.example.getbook.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Controller
@RequestMapping("/tt")
public class ToutiaoController {

    @Autowired
    public RestTemplate restTemplate;

    @ResponseBody
    @RequestMapping(value = "/get")
    public JSONObject get(HttpServletRequest request, String downloadPath, String startUrl, Long sleepSec) throws IOException, InterruptedException {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(null, headers);
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));

        ResponseEntity<String> response = null;
        while(response == null){
            try {
                response = restTemplate.exchange(
                        "https://www.toutiao.com/w/1733888301559892/?log_from=c7ec222a21f34_1655119343740"
                        , HttpMethod.GET, httpEntity, String.class);
            }catch (Exception e){
                e.printStackTrace();
                Thread.sleep(10*1000L);
            }
        }
        String  html = response.getBody();
        System.out.println();
        JSONObject object = new JSONObject();
        object.put("success",html);
        return object;
    }
}
